const random = require('random')
const securityUtil = require('../util/security')
const { User } = require('../db')

function genRandomCode () {
  const f = random.int(1, 10)
  const l = random.int(0, 100000)
  return f * 100000 + l
}

async function generateEmailToken (ctx, next) {
  const { email } = ctx.request.body
  const user = await User.findOne({
    email
  })
  if (!user) {
    ctx.throw('该邮箱未绑定任何用户!')
  }
  const code = genRandomCode()
  const genTime = Date.now()
  const token = securityUtil.getSecret(`${genTime}${code}${user.password}`)
  ctx.tl = {
    code,
    token,
    email,
    genTime,
    username: user.username
  }
  await next()
}

async function verifyEmailToken (ctx, next) {
  const { token, genTime, code, email } = ctx.request.body
  const user = await User.findOne({
    email
  })
  if (!user) {
    ctx.throw('该邮箱未绑定任何用户!')
  }
  const genToken = securityUtil.getSecret(`${genTime}${code}${user.password}`)
  if (token !== genToken) {
    ctx.throw('invalid token')
  }
  if (Date.now() - genTime > 5 * 60 * 1000) {
    ctx.throw('expired token')
  }

  ctx.tl = {
    ...user._doc
  }

  await next()
}

module.exports = {
  generateEmailToken,
  verifyEmailToken
}
